<template>
  <div class="containe">
    <div class="button-container">
      <el-button type="primary" @click="dialogVisible = true" v-if="isAdmin">添加管理员</el-button>
    </div>
    <el-table
      :data="tableData"
      style="width: 100%">
      <el-table-column prop="username" label="账号"> </el-table-column>
      <el-table-column prop="password" label="密码"> </el-table-column>
      <el-table-column prop="role" label="角色"> 
        <template slot-scope="{row}">
          {{ row.role === 1 ? '超级管理员' : '普通管理员' }}
        </template>
      </el-table-column>
      <el-table-column prop="created" label="创建时间"> 
          <template slot-scope="{row}">
            {{ row.created | formatDate }}
          </template>
      </el-table-column>
      <el-table-column prop="updated" label="更新时间"> 
          <template slot-scope="{row}">
            {{ row.updated | formatDate }}
          </template>
      </el-table-column>
      <el-table-column label="操作"> 
        <template slot-scope="{row}">
          <el-button type="danger" @click="deleteUser(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="添加书籍管理员" :visible.sync="dialogVisible">
      <div>
        <el-form :label-position="labelPosition" label-width="80px">
        <el-form-item label="账号">
          <el-input v-model="newAdmin.username"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="newAdmin.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="newAdmin.role" placeholder="请选择角色">
            <el-option label="超级管理员" :value="1"></el-option>
            <el-option label="普通管理员" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>


</template>

<style lang="scss">
.containe {
  padding: 20px;
  background-color: #fff;
  height: 95%;
  
  .button-container {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 20px;
    
    .el-button {
      padding: 10px 20px;
    }
  }
  
  .el-table {
    margin-top: 0;
    
    .el-table__header-wrapper {
      height: 60px; 
      line-height: 60px;
      font-size: 20px;
      
      th.el-table__cell {
        padding: 4px 0;  
      }
    }
    
    .el-table-column {
      line-height: 1.4;  
    }
  }
}
</style>

<script>
export default {
  data() {
    return {
      isAdmin: false,
      tableData: [],
      dialogVisible: false,
      newAdmin: {
        username: '',
        password: '',
        role: 0
      }
    };
  },
  created() {
    this.getAdminList();
  },
  methods: {
    getAdminList() {
      const xhr = new XMLHttpRequest();
      xhr.open("POST", "http://localhost:3000/api/admins");
      xhr.setRequestHeader("Content-Type", "application/json");

      xhr.onload = () => {
        if (xhr.status === 200) {
          try {
            const response = JSON.parse(xhr.responseText);
            if (response.success) {
              this.tableData = response.data;
              // 设置当前用户是否为超级管理员
              const currentUser = response.data.find(admin => admin.username === localStorage.getItem('username'));
              if (currentUser && currentUser.role === 1) {
                this.isAdmin = true;
              }
            } else {
              this.$message.error(response.message || '加载失败');
            }
          } catch (e) {
            console.error('JSON解析失败:', e);
            this.$message.error('服务器返回异常');
          }
        } else {
          console.error('请求失败:', xhr.statusText);
        }
      };

      xhr.onerror = () => {
        console.error('请求错误');
      };

      xhr.send(JSON.stringify({}));
    },

    addUser() {
      const xhr = new XMLHttpRequest();
      xhr.open("POST", "http://localhost:3000/api/admins/add");
      xhr.setRequestHeader("Content-Type", "application/json");

      xhr.onload = () => {
        if (xhr.status === 200) {
          try {
            const response = JSON.parse(xhr.responseText);
            if (response.success) {
              this.$message.success(response.message || '添加成功');
              this.dialogVisible = false;
              this.getAdminList(); // 刷新管理员列表
            } else {
              this.$message.error(response.message || '添加失败');
            }
          } catch (e) {
            console.error('JSON解析失败:', e);
            this.$message.error('服务器返回异常');
          }
        } else {
          console.error('请求失败:', xhr.statusText);
          this.$message.error('网络错误');
        }
      };

      xhr.onerror = () => {
        console.error('请求错误');
        this.$message.error('网络请求错误');
      };

      xhr.send(JSON.stringify(this.newAdmin));
    },

   deleteUser(row) {
  this.$confirm('确定要删除该管理员吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const xhr = new XMLHttpRequest();
    const url = `http://localhost:3000/api/admins/delete?username=${encodeURIComponent(row.username)}`;
    
    // 打开GET请求
    xhr.open("GET", url);
    
    // 设置响应处理
    xhr.onload = () => {
      console.log('响应状态:', xhr.status, '响应内容:', xhr.responseText);
      
      if (xhr.status === 200) {
        try {
          const response = JSON.parse(xhr.responseText);
          
          if (response.success) {
            this.$message.success(response.message || '删除成功');
            // 刷新管理员列表
            this.getAdminList();
          } else {
            this.$message.error(response.message || '删除失败');
          }
        } catch (e) {
          console.error('JSON解析失败:', e);
          this.$message.error('服务器返回异常');
        }
      } else if (xhr.status === 404) {
        this.$message.error('接口不存在，请检查后端路由');
      } else {
        this.$message.error(`请求失败: ${xhr.statusText}`);
      }
    };
    
    // 设置错误处理
    xhr.onerror = () => {
      console.error('请求错误详情:', {
        status: xhr.status,
        statusText: xhr.statusText,
        readyState: xhr.readyState
      });
      this.$message.error('网络请求失败，请检查后端服务是否运行');
    };
    
    // 发送请求
    xhr.send();
    
  }).catch(() => {
    this.$message.info('已取消删除');
  });
}
  },
  filters: {
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} 
              ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
    }
  }
};
</script>
